<template>
  <div class="max-w-screen-xl mx-auto h-full overflow-y-auto">
    <div class="bg-slate-50 p-2 pt-2 min-h-full">
      <div class="flex justify-between items-center">
        <el-tabs v-model="activeName" class="flex-1">
          <el-tab-pane label="批量查询" name="batch"></el-tab-pane>
          <el-tab-pane label="查询用户" name="user"></el-tab-pane>
        </el-tabs>
        <el-icon
          style="margin-bottom: 15px"
          size="20"
          class="cursor-pointer"
          @click="setParams"
        >
          <Setting />
        </el-icon>
      </div>

      <el-form class="flex flex-wrap" inline>
        <template v-if="collapseVisible">
          <el-form-item v-if="isBatch" label="召唤师">
            <el-select
              v-model="roles"
              multiple
              collapse-tags
              clearable
              placeholder="请选择召唤师"
            >
              <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <template v-else>
            <el-form-item label="召唤师名称">
              <el-input
                v-model="nickname"
                clearable
                placeholder="召唤师名称"
                style="width: 200px"
              ></el-input>
            </el-form-item>

            <el-form-item v-if="!isBatch" label="大区">
              <el-select v-model="areaId" placeholder="请选择大区">
                <el-option
                  v-for="item in areaList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>

          <el-form-item label="日期">
            <el-date-picker
              v-model="dataRange"
              @change="datePickerChange"
              value-format="YYYY-M-D"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 260px"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="总局数">
            <el-input-number
              v-model="num"
              :step="1"
              :min="1"
              :max="1000"
              step-strictly
              placeholder="总局数"
            ></el-input-number>
          </el-form-item>

          <el-form-item label="游戏模式">
            <el-select v-model="competitionType" placeholder="请选择游戏模式">
              <el-option
                v-for="item in CompetitionTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="isBatch"
              type="primary"
              @click="getSO1History"
              :loading="loading"
            >
              批量查询
            </el-button>

            <template v-else>
              <el-button
                type="primary"
                @click="getHistoryOne"
                :loading="loading"
                >查询</el-button
              >
              <el-button type="primary" @click="insert"
                >添加到批量查询</el-button
              >
            </template>
            <el-button v-if="isBatch" type="success" @click="save"
              >缓存数据</el-button
            >
          </el-form-item>
        </template>

        <div>
          <el-select
            v-if="isBatch"
            v-model="mode"
            @change="modeChange"
            placeholder="模式"
            class="w-20 mx-2"
          >
            <el-option
              v-for="item in modeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>

          <el-button v-if="isBatch" plain type="warning" @click="edit">{{
            editStatus ? '完成编辑' : '编辑'
          }}</el-button>
          <el-button v-if="isBatch" plain type="success" @click="handleShare"
            >截图</el-button
          >
          <el-button plain type="danger" class="mr-4" @click="clear">
            清空
          </el-button>
        </div>
        <el-form-item>
          <div class="flex gap-2 flex-wrap" v-if="!isBatch">
            <el-tag
              class="cursor-pointer"
              v-for="tag in searchHistory"
              :key="tag"
              closable
              :disable-transitions="false"
              @click="selectHistory(tag)"
              @close="handleClose(tag)"
            >
              {{ tag?.nickname }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>

      <div class="shot">
        <div v-if="isBatch">{{ showDate }}</div>
        <RecordList
          v-if="isBatch"
          v-loading="shareLoading"
          :class="{ share: shareLoading }"
          :mode="mode"
          :list="tableData1"
          :editStatus="editStatus"
        />

        <RecordCard v-else :recordData="recordData" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onActivated, nextTick } from 'vue'
import throttle from 'lodash/throttle'
import { searchPlayerAll, leagueSummoner, history_all } from '@/axios/api.js'
import { areaMap, defaultUser } from '@/utils/area.js'
import { ElMessage } from 'element-plus'
import { Setting } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

import RecordCard from './components/RecordCard.vue'
import RecordList from './components/RecordList.vue'
import {
  getSign,
  addUserList,
  addSelectedUserList,
  handlerso1Data,
  parseTime,
  handlerMerge
} from '@/utils/auth'
import screenshot from '@/utils/screenshot'

const areaList = Object.values(areaMap)
const collapseVisible = ref(true)
const activeName = ref('batch')
const loading = ref(false)
const nickname = ref('')
const competitionType = ref('450')
const areaId = ref('4')
const shareLoading = ref(false)

const mode = ref('normal')
const modeOption = [
  { label: '极简', value: 'mini' },
  { label: '普通', value: 'normal' },
  { label: '详细', value: 'detailed' }
]
const dataRange = ref([])
const num = ref(10)
const tableData1 = ref([])
const recordData = ref({
  totalGames: 0,
  wins: 0,
  losses: 0,
  rate: 0,
  mvp: 0,
  svp: 0,
  svpRate: 0,
  mvpRate: 0,
  matchNum: 0,
  aramNum: 0,
  rankNum: 0,
  teamNum: 0,
  blackoutTimes: 0,
  twoBlack: 0,
  threeBlack: 0,
  fourBlack: 0,
  fiveBlack: 0,
  blackoutWins: 0,
  twoBlackWins: 0,
  threeBlackWins: 0,
  fourBlackWins: 0,
  fiveBlackWins: 0
})

const CompetitionTypeOption = ref([
  { value: '', label: '全部比赛' },
  { value: '420', label: '排位赛' },
  { value: '440', label: '灵活排位' },
  { value: '430', label: '匹配赛' },
  { value: '450', label: '大乱斗' }
])

const roles = ref([])

const searchHistory = ref([])
const handleClose = tag => {
  searchHistory.value.splice(searchHistory.value.indexOf(tag), 1)
  localStorage.setItem(
    'searchHistoryLocal',
    JSON.stringify(searchHistory.value)
  )
}

// 选择历史用户tag
const selectHistory = tag => {
  if (loading.value) return
  console.log('选择', tag)
  nickname.value = tag.nickname
  areaId.value = tag.areaId
  competitionType.value = tag.filter
  getHistoryOne()
}

const options1 = ref([...defaultUser])

// 展示模式切换
function modeChange(val) {
  localStorage.setItem('displayMode', val)
}

function initDate() {
  const day = new Date().getDate()
  const year = new Date().getFullYear()
  const month = new Date().getMonth() + 1
  if (day === 1) {
    dataRange.value = [`${year}-${month}-1`, `${year}-${month}-2`]
  } else {
    dataRange.value = [`${year}-${month}-1`, `${year}-${month}-${day}`]
  }
  num.value = calculationSessions()
}

onMounted(() => {
  const lol = localStorage.getItem('lol')
  try {
    if (lol && Array.isArray(JSON.parse(lol))) {
      tableData1.value = JSON.parse(lol)
    }
  } catch (error) {
    console.log('缓存的默认批量战绩错误', error)
  }
  const singlePlayerRecord = localStorage.getItem('singlePlayerRecord')
  try {
    if (singlePlayerRecord && JSON.parse(singlePlayerRecord)) {
      recordData.value = JSON.parse(singlePlayerRecord)
      console.log('哇哈哈', recordData.value)
    }
  } catch (error) {
    console.log('缓存的单人战绩错误', error)
  }
  const searchHistoryLocal = localStorage.getItem('searchHistoryLocal')
  try {
    if (searchHistoryLocal && Array.isArray(JSON.parse(searchHistoryLocal))) {
      searchHistory.value = JSON.parse(searchHistoryLocal)
    }
  } catch (error) {
    console.log('缓存的历史搜索', error)
  }
  try {
    const displayMode = localStorage.getItem('displayMode')
    if (displayMode) {
      mode.value = displayMode
    }
  } catch (error) {
    console.log('展示模式', error)
  }
  // 初始化日期
  initDate()
  addSelectedUser()
})

onActivated(() => {
  addUserOptions()
})

const router = useRouter()
function setParams() {
  router.push('/settings')
}

function addUserOptions() {
  // 批量查询增加额外的召唤师
  const userList = localStorage.getItem('userList')
  try {
    if (userList && Array.isArray(JSON.parse(userList))) {
      options1.value = [...defaultUser, ...JSON.parse(userList)]
    }
  } catch (error) {
    console.log('添加召唤师报错', error)
  }
}

function addSelectedUser() {
  // 批量查询增加额外的召唤师
  const selectedUserList = localStorage.getItem('selectedUserList')
  try {
    if (selectedUserList && Array.isArray(JSON.parse(selectedUserList))) {
      roles.value = [...JSON.parse(selectedUserList)]
    }
  } catch (error) {
    console.log('添加默认选中召唤师报错', error)
  }
}

const showDate = computed(() => {
  if (dataRange.value && dataRange.value.length) {
    return `${formatMsToDate(dataRange.value[0])}—${formatMsToDate(dataRange.value[1])}`
  } else {
    return ''
  }
})

// 是否是批量查询
const isBatch = computed(() => activeName.value === 'batch')

function toggleCollapse() {
  collapseVisible.value = !collapseVisible.value
}

function addZero(num) {
  return parseInt(num) < 10 ? '0' + num : num
}

function handleShare() {
  shareLoading.value = true

  nextTick(() => {
    screenshot('.shot', '战绩列表').finally(() => (shareLoading.value = false))
  })
}

function formatMsToDate(ms) {
  if (ms) {
    const oDate = new Date(ms)
    const oYear = oDate.getFullYear()
    const oMonth = oDate.getMonth() + 1
    const oDay = oDate.getDate()
    return `${oYear}-${addZero(oMonth)}-${addZero(oDay)}`
  } else {
    return ''
  }
}

function save() {
  localStorage.setItem('lol', JSON.stringify(tableData1.value))
  ElMessage({
    message: '缓存成功',
    type: 'success'
  })
}

// 清空列表数据
function clear() {
  tableData1.value = []
  localStorage.removeItem('lol')
}

// 编辑
const editStatus = ref(false)
function edit() {
  if (editStatus.value) {
    editStatus.value = false
  } else {
    editStatus.value = true
  }
}

function datePickerChange() {
  console.log('日期', dataRange.value)
  num.value = calculationSessions()
}

function divideBy200(num) {
  const base = 200
  const result = []

  // 计算有多少个完整的200
  const fullParts = Math.floor(num / base)

  // 将完整的200添加到结果数组中
  for (let i = 0; i < fullParts; i++) {
    result.push(base)
  }

  // 计算剩余的部分
  const remainder = num % base

  // 如果剩余部分不为0，则将其添加到结果数组中
  if (remainder > 0) {
    result.push(remainder)
  }

  return result
}

const showErrorMessage = message => {
  ElMessage({
    message: message,
    type: 'error'
  })
}

const errorMessage = throttle(showErrorMessage, 1000, { trailing: false })
async function getSO1History() {
  const allrequestParams = options1.value.filter(v =>
    roles.value.includes(v.value)
  )
  // console.log('allrequestParams', allrequestParams);
  const countList = divideBy200(num.value)
  const allrequest = allrequestParams.map(async v => {
    try {
      const res1 = await leagueSummoner({
        area: areaMap[v.areaId]?.name,
        gameName: v.label,
        tagLine: v.tagLine
      })
      console.log('第一次请求', res1)

      if (res1?.success === false) {
        // ElMessage({
        //   message: res1?.error?.message,
        //   type: 'error'
        // })
        errorMessage(res1?.error?.message)
        return
      }
      const data = res1?.data
      const accumulatedMatches = []
      for (let i = 0; i < countList.length; i++) {
        const res2 = await history_all({
          area: areaMap[v.areaId]?.name,
          puuid: data.puuid,
          beginIdx: 200 * i,
          count: countList[i]
        })
        accumulatedMatches.push(...res2.data)
      }
      return { baseInfo: data, list: accumulatedMatches }
    } catch (error) {
      console.log('错误2', error)
    }
  })
  let resp = null
  try {
    loading.value = true
    resp = await Promise.all(allrequest)
    console.log('相应', resp)

    let newData = resp.map((v, idx) => {
      return {
        ...allrequestParams[idx],
        ...handlerso1Data({
          ...v,
          allrequestParams: allrequestParams,
          ...allrequestParams[idx],
          queueId: competitionType.value,
          dataRange: dataRange.value
        })
      }
    })
    newData = handlerMerge(newData)
    newData.forEach(y => {
      const findIdx = tableData1.value.findIndex(v => y.value === v.value)
      if (findIdx !== -1) {
        tableData1.value[findIdx] = y
      } else {
        tableData1.value.push(y)
      }
    })
    console.log('中级接口过', newData)
    ElMessage({
      message: '查询成功！！',
      type: 'success'
    })
  } catch (error) {
    console.log('有错误', error)
  } finally {
    // console.log("最终结果新", resp);
    loading.value = false
    // uni.setStorageSync("searchLogs", JSON.stringify(resp));
  }
}

function insert() {
  console.log('插入数据', recordData.value)
  if (recordData.value?.name) {
    const flag = options1.value.some(
      item => item.value === recordData.value.puuid
    )
    if (!flag) {
      addUserList({
        label: recordData.value?.name,
        tagLine: recordData.value?.tagLine,
        areaId: recordData.value?.areaId,
        value: recordData.value?.puuid
      })
      addSelectedUserList(recordData.value?.puuid)
      addUserOptions()
      addSelectedUser()

      ElMessage({
        message: '添加成功',
        type: 'success'
      })
    }
  }
}

function getHistoryOne() {
  console.log('大区', areaId.value)
  const { name: areaName } = areaMap[areaId.value]
  const nicknameArr = nickname.value?.split('#')
  if (!nickname.value) {
    ElMessage({
      message: '请输入召唤师名称',
      type: 'error'
    })
    return
  }
  if (nicknameArr.length < 2) {
    ElMessage({
      message: '召唤师名称需要加上尾标(#12345)',
      type: 'error'
    })
    return
  }
  if ((!dataRange.value || dataRange.value.length != 2) && !num.value) {
    ElMessage({
      message: '请输入日期或者总局数',
      type: 'error'
    })
    return
  }
  loading.value = true
  leagueSummoner({
    area: areaName,
    gameName: nicknameArr[0],
    tagLine: nicknameArr[1]
  })
    .then(res => {
      console.log('单个查询', res)
      if (res?.success === false) {
        ElMessage({
          message: res?.error?.message,
          type: 'error'
        })
        return
      }

      recordData.value = {
        ...res?.data,
        name: nicknameArr[0],
        tagLine: nicknameArr[1],
        areaId: areaId.value,
        publicInfo: res?.data?.privacy === 'PUBLIC' ? '公开' : '隐藏',
        onlineInfo: parseTime(res?.data?.lastGameDate - 8 * 3600 * 1000)
      }
    })
    .finally(() => {
      loading.value = false
    })
}

function calculationSessions() {
  if (!dataRange.value || !dataRange.value.length) {
    return 1
  }
  const timeDifference =
    new Date(dataRange.value[1]).getTime() -
    new Date(dataRange.value[0]).getTime() +
    1000 * 3600 * 24
  const days = Math.ceil(timeDifference / (1000 * 3600 * 24))
  console.log('打印days', days)
  if (days === 1) {
    return 20
  } else if (days < 4) {
    return days * 15
  } else if (days < 6) {
    return days * 10
  } else if (days < 20) {
    return days * 7
  } else if (days < 30) {
    return days * 6
  } else {
    return 200
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  width: 200px;
}

.share {
  :deep(.record-close) {
    display: none;
  }

  :deep(.record-item) {
    box-shadow: none !important;
  }

  :deep(.record-title) {
    display: block !important;
  }
}
</style>
